<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Sales\Entity\Order;
use Sales\Entity\OrderDeliveryAddress;
use Sales\Entity\OrderGoods;
use Sales\Form\ExportSalesShipForm;
use Sales\Form\SearchOrderShipForm;

class ShipController extends AdminActionController
{
    private $translator;
    private $entityManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
    }

    /**
     * 订单发货单列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchForm = new SearchOrderShipForm();
        $searchForm->get('express_state')->setValueOptions([1 => $this->translator->translate('已发货'), 2 => $this->translator->translate('未发货')]);
        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) $search = $searchForm->getData();
        }

        $query      = $this->entityManager->getRepository(OrderDeliveryAddress::class)->findOrderShipList($search);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return ['shipList' => $paginator, 'searchForm' => $searchForm];
    }

    /**
     * 发货单详情
     * @return array|\Laminas\Http\Response
     */
    public function detailAction()
    {
        $orderId    = (int) $this->params()->fromRoute('id', -1);
        $orderInfo  = $this->entityManager->getRepository(Order::class)->findOneBy(['orderId' => $orderId]);
        if ($orderInfo == null || $orderInfo->getDeliveryType() != 'delivery') {
            return $this->redirect()->toRoute('sales-ship');
        }

        $queryData = $this->params()->fromQuery();

        $orderDeliveryInfo = $this->entityManager->getRepository(OrderDeliveryAddress::class)->findOneBy(['orderId' => $orderId]);
        if ($orderDeliveryInfo == null) return $this->redirect()->toRoute('sales-ship');

        return ['queryData' => $queryData, 'orderInfo' => $orderInfo, 'deliveryAddress' => $orderDeliveryInfo];
    }

    /**
     * 发货单导出
     * @return \Laminas\Http\PhpEnvironment\Response|\Laminas\Stdlib\ResponseInterface|mixed|ExportSalesShipForm[]
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function exportSalesShipAction()
    {
        $form = new ExportSalesShipForm();
        $form->get('deliveryType')->setValueOptions($this->adminCommon()->deliveryNameOptions($this->translator->translate('全部方式')));
        $form->get('shipState')->setValueOptions([0 => $this->translator->translate('全部状态'), 1 => $this->translator->translate('已发货'), 2 => $this->translator->translate('未发货')]);

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $searchData = ['express_state' => $data['shipState'], 'delivery_id' => $data['deliveryType'], 'start_time' => $data['startTime'], 'end_time' => $data['endTime']];

                $query = $this->entityManager->getRepository(OrderDeliveryAddress::class)->findOrderShipList($searchData);
                $shipList = $query->getResult();
                if ($shipList) {
                    $spreadsheet= new Spreadsheet();
                    $spreadsheet->getProperties()->setCreator('DBShop');
                    $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(30);
                    $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(70);
                    $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(30);
                    $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(30);
                    $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(30);
                    $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(30);
                    $spreadsheet->getActiveSheet()->getColumnDimension('G')->setWidth(30);
                    $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth(30);
                    $spreadsheet->getActiveSheet()->getColumnDimension('I')->setWidth(30);
                    $spreadsheet->getActiveSheet()->getColumnDimension('J')->setWidth(30);

                    $sheet      = $spreadsheet->getActiveSheet();
                    $sheet->setCellValue('A1', $this->translator->translate('订单编号'));
                    $sheet->setCellValue('B1', $this->translator->translate('订单商品'));
                    $sheet->setCellValue('C1', $this->translator->translate('订单备注'));
                    $sheet->setCellValue('D1', $this->translator->translate('收货人'));
                    $sheet->setCellValue('E1', $this->translator->translate('收货地址'));
                    $sheet->setCellValue('F1', $this->translator->translate('联系方式'));
                    $sheet->setCellValue('G1', $this->translator->translate('邮政编码'));
                    $sheet->setCellValue('H1', $this->translator->translate('送货时间'));
                    $sheet->setCellValue('I1', $this->translator->translate('配送方式'));
                    $sheet->setCellValue('J1', $this->translator->translate('配送单号'));

                    $num = 2;
                    foreach ($shipList as $shipValue) {
                        $sheet->setCellValueByColumnAndRow(1, $num, $shipValue['orderSn']);

                        $orderGoodsStr  = '';
                        $orderGoodsList = $this->entityManager->getRepository(OrderGoods::class)->findBy(['orderId' => $shipValue[0]->getOrderId()]);
                        foreach ($orderGoodsList as $goodsValue) {
                            $orderGoodsStr .= $goodsValue->getGoodsName() . '('.$goodsValue->getGoodsItem().')' . ($goodsValue->getInSpecGoodsId() > 0 ? ' ['.$goodsValue->getInSpecGoodsStr().']' : '') . ' * ' . $goodsValue->getBuyNum() . "\r\n";
                        }

                        $sheet->setCellValueByColumnAndRow(2, $num, rtrim($orderGoodsStr, "\r\n"))->getStyle('B'.$num)->getAlignment()->setWrapText(true);
                        $sheet->setCellValueByColumnAndRow(3, $num, $shipValue['orderMessage']);
                        $sheet->setCellValueByColumnAndRow(4, $num, $shipValue[0]->getTrueName());
                        $sheet->setCellValueByColumnAndRow(5, $num, $shipValue[0]->getRegionValue() . $shipValue[0]->getAddressInfo());
                        $sheet->setCellValueByColumnAndRow(6, $num, Common::areaPhoneCode($shipValue[0]->getAreaCode()) . ' ' . $shipValue[0]->getPhone());
                        $sheet->setCellValueByColumnAndRow(7, $num, $shipValue[0]->getPostCode()."\t");
                        $sheet->setCellValueByColumnAndRow(8, $num, $shipValue[0]->getDeliveryTimeInfo());
                        $sheet->setCellValueByColumnAndRow(9, $num, $shipValue['deliveryName']);
                        $sheet->setCellValueByColumnAndRow(10, $num, $shipValue['expressNumber']."\t");
                        $num++;
                    }

                    $response   = $this->getResponse();
                    $headers    = $response->getHeaders();
                    $headers->addHeaderLine("Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    $headers->addHeaderLine("Content-Disposition: attachment;filename=".$this->translator->translate('发货单').".xlsx");
                    $headers->addHeaderLine("Cache-Control: max-age=0");
                    $response->sendHeaders();

                    $writer = new Xlsx($spreadsheet);
                    return $response->setContent($writer->save('php://output'));
                }
            }
        }

        return ['form' => $form];
    }
}